package com.nnggstory.logs.logsocket;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nnggstory.logs.common.IServer;
import com.nnggstory.logs.websocket.WebSocketPushServer;

public class LoggerSocketServer extends Thread implements IServer {
	public static final int DEFAULT_PORT = 1095;
	private static final Logger logger = LoggerFactory.getLogger(LoggerSocketServer.class);
    private final int port;
    private Map<String, Object> serverContext = null;

    public LoggerSocketServer(int port) {
        this.port = port;
    }

    public LoggerSocketServer() {
        this(DEFAULT_PORT);
    }

    @SuppressWarnings("unchecked")
	@Override
    public final void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            while (true) {
                Socket socket = serverSocket.accept();
                
                logger.info("From" + socket.getInetAddress() + ":" + socket.getPort() + " LoggerSocket Connected");
                Thread thread = new LogConnectThread(socket, (WebSocketPushServer)serverContext.get("WebSocketServer"), (Set<Socket>)serverContext.get("loggerClients"));
                thread.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	@Override
	public int getPort() {
		return port;
	}

	@Override
	public void serverStart() {
		start();
	}

	@Override
	public void setContext(Map<String, Object> context) {
		serverContext = context;
	}
}